﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkDownFileSplitter.Htm
{
    internal class CatalogTreeHandler
    {
        public TreeNodeCollection RootNodes { get; set; }

        public CatalogTreeHandler(TreeNodeCollection rootNodes)
        {
            RootNodes = rootNodes;
        }

        public void HandleHeadingLevel1(HtmSelectionObject htmSelectionObject)
        {
            if (RootNodes.Count == 0)//未有一级标题的情况
            {
                TreeNode rootNode = new TreeNode();
                rootNode.Text = htmSelectionObject.Text;
                rootNode.Tag = new HtmCatalogTreeItem(htmSelectionObject.StartIndex, htmSelectionObject.EndIndex, false, htmSelectionObject.Text, int.MaxValue);
                RootNodes.Add(rootNode);
            }
            else//已有一级标题的情况
            {
                bool ifRelace = ReplaceAutoGenerateNode(RootNodes, htmSelectionObject);
                if (!ifRelace)
                {
                    AddNewNode(RootNodes, htmSelectionObject, null);
                }
            }
        }

        public void HandleHeadingLevel2(HtmSelectionObject htmSelectionObject)
        {
            //查看有没有合适的一级节点，没有则需要创建对应的一级节点
            TreeNode level1Node = null;

            // 查找合适的一级节点
            foreach (TreeNode node in RootNodes)
            {
                var item = (HtmCatalogTreeItem)node.Tag;
                if (htmSelectionObject.StartIndex > item.StartIndex && htmSelectionObject.EndIndex < item.ContainsEndIndex)
                {
                    level1Node = node;
                    break;
                }
            }

            // 如果没有找到合适的一级节点，则创建一个新的一级节点
            if (level1Node == null)
            {
                level1Node = AddNewNode(RootNodes, htmSelectionObject, null, true, "一级临时节点");
                AddNewNode(level1Node.Nodes, htmSelectionObject, level1Node);
            }
            else
            {
                //如果找到了合适的，则需要判断是Replace某个临时节点还是新增节点
                bool ifRelace = ReplaceAutoGenerateNode(level1Node.Nodes, htmSelectionObject);
                if (!ifRelace)
                {
                    AddNewNode(level1Node.Nodes, htmSelectionObject, level1Node);
                }
            }
        }

        public void HandleHeadingLevel3(HtmSelectionObject htmSelectionObject)
        {
            //查找是否有合适的一级节点和二级节点，没有则需要创建对应的一级节点和二级节点
            TreeNode level1Node = null;
            TreeNode level2Node = null;

            // 查找合适的一级节点
            foreach (TreeNode node in RootNodes)
            {
                var item = (HtmCatalogTreeItem)node.Tag;
                if (htmSelectionObject.StartIndex > item.StartIndex && htmSelectionObject.EndIndex < item.ContainsEndIndex)
                {
                    level1Node = node;
                    break;
                }
            }

            // 如果没有找到合适的一级节点，则创建一个新的一级节点
            if (level1Node == null)
            {
                level1Node = AddNewNode(RootNodes, htmSelectionObject, null, true, "一级临时节点");
            }

            // 查找合适的二级节点
            foreach (TreeNode childNode in level1Node.Nodes)
            {
                var childItem = (HtmCatalogTreeItem)childNode.Tag;
                if (htmSelectionObject.StartIndex > childItem.StartIndex && htmSelectionObject.EndIndex < childItem.ContainsEndIndex)
                {
                    level2Node = childNode;
                    break;
                }
            }
            // 如果没有找到合适的二级节点，则创建一个新的二级节点
            if (level2Node == null)
            {
                level2Node = AddNewNode(level1Node.Nodes, htmSelectionObject, level1Node, true, "二级临时节点");
            }

            AddNewNode(level2Node.Nodes, htmSelectionObject, level2Node);
        }

        /// <summary>
        /// 替换临时节点
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="htmSelectionObject"></param>
        /// <returns></returns>
        private bool ReplaceAutoGenerateNode(TreeNodeCollection nodes, HtmSelectionObject htmSelectionObject)
        {
            foreach (TreeNode node in nodes)
            {
                var item = (HtmCatalogTreeItem)node.Tag;
                if (item.IsAutoGenerate == false)// 如果不是自动生成的节点，跳过
                    continue;

                //只要标题位置在临时节点的StartIndex前面，则判断为属于该临时节点的范围，取代该临时节点
                if (htmSelectionObject.StartIndex < item.StartIndex)
                {
                    node.Text = htmSelectionObject.Text;
                    item.IsAutoGenerate = false;
                    item.Text = htmSelectionObject.Text;
                    return true;
                }
            }
            return false;
        }

        private TreeNode AddNewNode(TreeNodeCollection nodes, HtmSelectionObject htmSelectionObject, TreeNode parentNode, bool autoGenerate = false, string text = "")
        {
            HtmCatalogTreeItem newItem;
            TreeNode newNode;
            if (autoGenerate)
            {
                newItem = new HtmCatalogTreeItem(htmSelectionObject.StartIndex, htmSelectionObject.EndIndex, true, text, parentNode == null ? int.MaxValue : ((HtmCatalogTreeItem)parentNode.Tag).ContainsEndIndex);
                newNode = new TreeNode
                {
                    Text = text,
                    Tag = newItem
                };
            }
            else
            {
                newItem = new HtmCatalogTreeItem(htmSelectionObject, parentNode == null ? int.MaxValue : ((HtmCatalogTreeItem)parentNode.Tag).ContainsEndIndex);
                newNode = new TreeNode
                {
                    Text = newItem.Text,
                    Tag = newItem
                };
            }

            int nodeIndex = -1;
            // 根据StartIndex插入到合适的位置
            for (int i = 0; i < nodes.Count; i++)
            {
                var existingItem = (HtmCatalogTreeItem)nodes[i].Tag;
                if (newItem.StartIndex < existingItem.StartIndex)
                {
                    if (existingItem.IsAutoGenerate)//判断是否能合并两个临时节点
                    {
                        existingItem.StartIndex = newItem.StartIndex;
                        existingItem.Text = newItem.Text;
                        nodes[i].Text = newItem.Text;
                        newNode = nodes[i];
                    }
                    else//普通情况
                    {
                        nodes.Insert(i, newNode);
                    }
                    nodeIndex = i;
                    break;
                }
            }

            if (nodeIndex == -1)
            {
                // 如果没有找到合适的位置，则添加到最后
                nodeIndex = nodes.Add(newNode);
            }

            //插入新节点后，需要检查是否接替部分子Node
            if (nodeIndex > 0)
            {
                //只需判断上一个同级节点的子节点
                var previousNode = nodes[nodeIndex - 1];
                for (int i = previousNode.Nodes.Count - 1; i >= 0; i--)
                {
                    TreeNode childOfPreviousNode = previousNode.Nodes[i];
                    var childItem = (HtmCatalogTreeItem)childOfPreviousNode.Tag;
                    if (childItem.StartIndex > newItem.StartIndex)
                    {
                        previousNode.Nodes.RemoveAt(i);
                        newNode.Nodes.Insert(0, childOfPreviousNode);//由于是倒序遍历，所以每次都插入最前面
                    }
                }

                //还需要修改上一个同级节点的EndIndex
                var previousItem = (HtmCatalogTreeItem)previousNode.Tag;
                previousItem.ContainsEndIndex = newItem.StartIndex - 1;
            }

            //如果后面还有同级节点，则需要修改自己的EndIndex
            if (nodeIndex < nodes.Count - 1)
            {
                var nextItem = (HtmCatalogTreeItem)nodes[nodeIndex + 1].Tag;
                newItem.ContainsEndIndex = nextItem.StartIndex - 1;
            }

            return newNode;
        }
    }
}
